import { MenuVoInfo } from '#/entity';
import { Tree, TreeDataNode } from 'antd';
import { useTheme } from '@/store/settingsStore.ts';
import { EventDataNode } from 'antd/es/tree';
import { Key } from 'react';

type PermissionTreeProps = {
  value?: string[];
  onChange?: (value: string[]) => void;
  treeData: TreeDataNode[];
};

type CheckedKeys = {
  checked: string[];
  halfChecked: string[];
};

type WrappedNode = EventDataNode<TreeDataNode> & {
  parentNode?: MenuVoInfo | null;
};

interface TreeNode {
  key: Key;
  children?: TreeNode[];
}

const PermissionTree = ({ treeData, value, onChange }: PermissionTreeProps) => {
  const theme = useTheme();
  return (
    <Tree
      className={theme}
      checkable
      height={224}
      checkStrictly
      checkedKeys={value}
      defaultExpandAll
      treeData={treeData}
      onCheck={(checkedKeys, { checked, node }) => {
        // console.log('checked =>', checked);
        // console.log('node =>', node);
        // console.log('treeData =>', treeData);

        const checkeds = (checkedKeys as CheckedKeys).checked;
        // console.log('checkeds =>', checkeds);

        const wrappedNode = node as WrappedNode;

        // 数组去重
        function removeDuplicates(arr: string[]): string[] {
          return Array.from(new Set(arr));
        }

        // 递归获取所有的 key
        function getAllKeys(node: TreeNode) {
          const keys: string[] = [];

          function traverse(node: TreeNode) {
            if (!node) return;
            keys.push(node.key as string);
            if (node.children && node.children.length > 0) {
              node.children.forEach((child) => traverse(child));
            }
          }

          if (node.children) {
            node.children.forEach((child) => traverse(child));
          }

          return keys;
        }

        // 查找根节点的 key
        function findRootKey(node: TreeNode[], childKey: string) {
          const recursionTree = (node: TreeNode[]): TreeNode[] => {
            return node.map((i) => ({
              key: i.key,
              children: i.children ? recursionTree(i.children) : [],
            }));
          };

          const tree = recursionTree(node);

          return tree.find((i) => i.children?.some((j) => j.key === childKey))?.key as
            | string
            | undefined;
        }

        // 操作根节点
        if (!wrappedNode.parentNode) {
          const keys = getAllKeys(wrappedNode);

          if (checked) {
            onChange?.(removeDuplicates([...checkeds, ...keys]));
          } else {
            const filteredKeys = checkeds.filter((i) => !keys.includes(i));
            onChange?.(removeDuplicates([...filteredKeys]));
          }
          return;
        }

        // 操作第二层节点
        if (wrappedNode.parentNode.parentId === 0) {
          if (checked) {
            const parentKey = wrappedNode.parentNode.menuPath;

            let childrenKeys: string[] = [];
            if (node.children && node.children.length > 0) {
              childrenKeys = node.children.map((i) => i.key as string);
            }

            onChange?.(removeDuplicates([...checkeds, parentKey, ...childrenKeys]));
          } else {
            let childrenKeys: string[] = [];

            if (node.children && node.children.length > 0) {
              childrenKeys = node.children.map((i) => i.key as string);
            }

            const filteredKeys = checkeds.filter((i) => !childrenKeys.includes(i));

            onChange?.(removeDuplicates([...filteredKeys]));
          }
        } else {
          // 操作叶子节点
          if (checked) {
            const parentKey = wrappedNode.parentNode.menuPath;
            const rootKey = findRootKey(treeData, parentKey);

            if (rootKey) {
              onChange?.(removeDuplicates([...checkeds, parentKey, rootKey]));
            }
          } else {
            onChange?.(removeDuplicates([...checkeds]));
          }
        }
      }}
    />
  );
};

export default PermissionTree;
